package com.example.huajia.wx.controller;

import com.example.huajia.wx.common.util.R;
import com.example.huajia.wx.config.shiro.JwtUtil;
import com.example.huajia.wx.controller.form.SearchAllProductByPageForm;
import com.example.huajia.wx.service.ProductService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.example.huajia.wx.common.util.RedisKey.PRODUCT_ALL_KEY;

@RestController
@RequestMapping("/product")
@Api("商品兑换接口")
public class ProductController {
    @Resource
    private ProductService productService;
    @Resource
    private JwtUtil jwtUtil;
    @Resource
    private RedisTemplate redisTemplate;
    @PostMapping("/searchAllProductByPage")
    @ApiOperation("分页查询商品接口")
    public R searchAllProductByPage(@Valid @RequestBody SearchAllProductByPageForm form, @RequestHeader("token") String token){
        //1.通过token获得UserId
        int userId = jwtUtil.getUserId(token);
        //2.将分页的参数page和length取出来
        Integer page = form.getPage();
        Integer length = form.getLength();
        //3.开始计算分页的开始位置
        long start = (page - 1) * length;
        long end = start + length - 1;
        //4.分别将userId、start、length放入HashMap中
        HashMap map = new HashMap();
        map.put("userId", userId);
        map.put("start", start);
        map.put("length", length);
        //先判断redis里面是否存在数据
        String key = PRODUCT_ALL_KEY;
        List range = redisTemplate.opsForList().range(key, start, end);
        if (range.isEmpty()){
            ArrayList<HashMap> list = productService.searchAllProductByPage(map);
            return R.ok().put("result", list);
        }
        //如果不为空，直接从redis取出数据返回给后端
        return R.ok().put("result", range);
    }
}
